from flask import Blueprint,render_template,jsonify,redirect,url_for,session
from exts import mail,db
from flask_mail import Message
from flask import request
import string
import random
from models import EmailCaptcha,UserModel
from .forms import RegisterForm,LoginForm
from werkzeug.security import generate_password_hash,check_password_hash
bp=Blueprint('auth', __name__, url_prefix="/auth")

@bp.route('/logout')
def logout():
    session.pop("user_id")
    return redirect("/")

@bp.route('/login',methods=["GET","POST"])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                return redirect(url_for("auth.login"))
            else:
                #第一个参数是数据库中的哈希密码，第二个参数是用户输入的密码
                if check_password_hash(user.password,password):
                    #cookie:只能存储小数据,登录授权
                    #flask的session是存储在cookie中的
                    session['user_id'] = user.id
                    return redirect("/")

                else:
                    print("密码错误")
                    return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))

#GET: 从服务器获取数据
#POST:将客户端数据提交服务器 405:请求错误
@bp.route("/register",methods=["GET","POST"])
def register():

    if request.method =="GET":
        return render_template("register.html")
    else:
        # 验证邮箱和验证码对应正确
        # 表单验证：flask_wtf
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("auth.login"))
            #return redirect("/auth/login")
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))

@bp.route("/captcha/email")
def get_email_captcha():
    #url传参 /<参数>
    #?email=XXX.qq.com
    email = request.args.get("email")
    #发送邮箱验证码
    src = string.digits*4
    captcha = random.sample(src,4)
    print(captcha)
    #['6', '3', '6', '4']转字符串
    captcha = "".join(captcha)
    #U/O操作多进程，为了前端更快的响应，任务队列
    message = Message(subject="注册验证码", recipients=[email], body=f"您的验证码是{captcha}")
    mail.send(message)
    # memcached/redis
    # 数据库存储
    email_captcha = EmailCaptcha(email=email,captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    #{code:200/400,msg:"",data:{}}
    return jsonify({"code":200,"msg":"验证码发送成功","data": None})

@bp.route("mail/test")
def mail_test():
    message = Message(subject="test mail", recipients=['13724510610@163.com'], body="这是一条测试邮件")
    mail.send(message)
    return "发送成功"